package net.yxsoft.service.formdisigner;

import com.jfinal.aop.Inject;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.mysql.jdbc.Connection;
import net.yxsoft.bean.FormDataExportFactroy;
import net.yxsoft.bean.SqlStringFactroy;
import net.yxsoft.enumclass.AuditStatusEnumCls;
import net.yxsoft.enumclass.FormDataRoleType;
import net.yxsoft.enumclass.WhetherEnumCls;
import net.yxsoft.kit.CustomDb;
import net.yxsoft.kit.Helper;
import net.yxsoft.kit.SnowFlakeIdUtil;
import net.yxsoft.kit.ToolDateTime;
import net.yxsoft.message.MessageKit;
import net.yxsoft.model.SLifecycExampleNode;
import net.yxsoft.model.formdesigner.FnFormData;
import net.yxsoft.model.formdesigner.FnFormDataRole;
import net.yxsoft.model.formdesigner.Form;
import net.yxsoft.model.formdesigner.FormField;
import net.yxsoft.model.infrastructure.TsMenu;
import net.yxsoft.quorum.MyERC721;
import net.yxsoft.quorum.QuorumKit;
import net.yxsoft.resource.*;
import net.yxsoft.service.common.BaseService;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.exceptions.TransactionException;
import org.web3j.utils.Numeric;
import rapid.core.Authuser;
import rapid.core.TResult;
import rapid.jfinal.Pagination;
import rapid.util.DateKit;
import rapid.util.StrKit;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author mlb
 */

public class FormDataService extends BaseService {

  @Inject
  FormDataRoleService rsv;
  public static final FormDataService SVC = new FormDataService();
  private FnFormData dao = new FnFormData().dao();

  /**
  * @MethodName: getAttribList
  * @Description: 获取当前表单还未绑定的字段
  * @param: formid
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 13:46
  * @author wj
  */
  public List<Record> getAttribList(String formid) {

    Record record=Db.findFirst("select * from fn_form where id=?",formid);
    List<Record> _returnData=null;
    if(record!=null && StrKit.notBlank(record.getStr("model"))){
      _returnData = Db.find("select concat(attrib_name,'|',attrib_type) name from ts_datamodel_properties a\n" +
              "inner join ts_party b on a.model_id = b.conflict_id\n" +
              "where b.name=? and a.attrib_name not in (select field from fn_form_field where form_id = ?)" +
              "order by a.id", record.getStr("model"),formid);
    }else {
      _returnData = Db.find("select concat(attrib_name,'|',attrib_type) name from ts_datamodel_properties a\n" +
              "inner join ts_party b on a.model_id = b.conflict_id\n" +
              "where b.name='fn_form_data' and a.attrib_name not in (select field from fn_form_field where form_id = ?)" +
              " and a.attrib_name not in ('attrib_01','attrib_02','attrib_101','attrib_102','attrib_103','attrib_104','attrib_99')\n" +
              "order by a.id", formid);
    }
    return _returnData;
  }


  /**
  * @MethodName: getFormFieldByFormid
  * @Description: 根据动态表单id获取设置的字段信息
  * @param: formid
  * @return * @return java.util.List<net.yxsoft.model.formdesigner.FormField>
  * @throws
  * @date 2023/8/31 13:47
  * @author wj
  */
  public List<FormField> getFormFieldByFormid(String formid) {
    List<FormField> _returnData = FormField.dao.find("select * from fn_form_field where form_id=? and State=1 order by sort desc", formid);
    return _returnData;
  }

  /**
  * @MethodName: CheckNodeIsTimeOut
  * @Description: 检查操作节点是否过期
  * @param: nodeid
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:47
  * @author wj
  */
  public TResult CheckNodeIsTimeOut(String nodeid) throws ParseException {
    SLifecycExampleNode _node = SLifecycExampleNode.dao.findById(nodeid);
    if (_node == null) {
      return fail().msg("当前节点不存在。");
    }

    if (_node.getAttrib14() == null) {
      return fail().msg("当前节点没有设置截止日期。");
    }
    //String _now = ToolDateTime.format(ToolDateTime.getDate(), "yyyy-MM-dd");

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String s = sdf.format(new Date());
    Date _now = sdf.parse(s);

    if (_node.getAttrib14().before(_now)) {
      return fail().msg("已过当前节点截止日期，不可再操作。");
    }

    return success();
  }


  /**
  * @MethodName: checkSelectAuthority
  * @Description: 获取查询权限--是否可查询全部数据，参与角色设置了全数据权限的可查全部
  * @param: user
   * @param: formid
  * @return * @return boolean
  * @throws
  * @date 2023/8/31 13:48
  * @author wj
  */
  public boolean checkSelectAuthority(Authuser user, String formid) {


    Record record = rsv.getFormDataUserRole(formid, user);

    if (record != null && WhetherEnumCls.YES.getValue().equals(record.getStr("attrib_15"))) {

      return true;
    }
    if (record != null && FormDataRoleType.Browse.getValue().equals(record.getStr("attrib_01"))) {

      return true;
    }
    if (record != null && FormDataRoleType.Audit.getValue().equals(record.getStr("attrib_01"))) {

      return true;
    }

    return false;


  }

  /**
  * @MethodName: sqlStringFactroy
  * @Description: 动态拼装SQL
  * @param: search
   * @param: sqlStringFactroy
   * @param: user
   * @param: dwkxz
   * @param: cid
  * @return * @return void
  * @throws
  * @date 2023/8/31 13:48
  * @author wj
  */
  public void sqlStringFactroy(Map<String, String[]> search, SqlStringFactroy sqlStringFactroy, Authuser user, String cid) {
    //查询Sql
    StringBuilder _strsql = new StringBuilder();
    StringBuilder _strsql_leftJoin = new StringBuilder();
    StringBuilder _strsql_col = new StringBuilder();
    StringBuilder _strwhere = new StringBuilder();

    //汇总Sql
    StringBuffer strsql_sum = new StringBuffer();
    StringBuilder strsql_sumcol = new StringBuilder();
    //分类汇总Sql
    StringBuffer strsql_typesum = new StringBuffer();
    StringBuffer strsql_typesumcol = new StringBuffer();
    Form form =Form.dao.findById( search.get("form_id")[0]);
    String typesumcol = "";

    List<String> _exportCol = new ArrayList<String>();
    List<String> _exportHead = new ArrayList<String>();

    int _CodeTableAS = 66;  //B的ASCII码
    if(form!=null && StrKit.notBlank(form.getModel())) {
      _strsql.append("SELECT A.conflict_id,A.ROW_ID,A.CREATED,A.CREATED_BY,A.LAST_UPD,A.LAST_UPD_BY,A.form_id,A.lifenode_id,A.audit_state,A.audit_by,A.audit_date,A.audit_by_name" +
              ",case when  A.audit_state='0'   then '待审核'\n" +
              "    when  A.audit_state='1'   then '审核通过'\n" +
              "\t\twhen  A.audit_state='-1'  then '不通过'\n" +
              "\t\twhen  A.audit_state='-9'  then '退回'\n" +
              "\t\twhen  A.audit_state='-2'  then '草稿'\n" +
              "\t\twhen  A.audit_state='-2'  then '草稿'\n" +
              "else '' end audit_state_cn,A.hash_val ");

      strsql_sum.append("SELECT * FROM (SELECT uuid() conflict_id,'-' ROW_ID,'1899-12-31' CREATED,\n" +
              "        '-' CREATED_BY,'-' CREATED_BY_NAME,'1899-12-31' LAST_UPD,'-' LAST_UPD_BY,'-' LAST_UPD_BY_NAME,\n" +
              "        '-' form_id, '-' lifenode_id, '-' audit_state,'-' audit_by, '1899-12-31' audit_date,'-' audit_by_name,'-' audit_state_cn,'-' hash_val ");

      strsql_typesum.append("SELECT uuid() conflict_id,'-' ROW_ID,'1899-12-31' CREATED,\n" +
              "        '-' CREATED_BY,'-' CREATED_BY_NAME,'1899-12-31' LAST_UPD,'-' LAST_UPD_BY,'-' LAST_UPD_BY_NAME,\n" +
              "        '-' form_id, '-' lifenode_id, '-' audit_state,'-' audit_by, '1899-12-31' audit_date,'-' audit_by_name,'-' audit_state_cn,'-' hash_val ");


      if (search.get("row_id") != null) {
        _strwhere.append(String.format(" WHERE A.MODIFICATION_NUM = 0 and A.form_id = '%s' and A.ROW_ID = '%s' ", search.get("form_id")[0], search.get("row_id")[0]));
      } else {
        _strwhere.append(String.format(" WHERE A.MODIFICATION_NUM = 0 and A.form_id = '%s' ", search.get("form_id")[0]));
      }


      if (search.get("keyid") != null && search.get("keyid").length > 0 && StrKit.notBlank(search.get("keyid")[0])) {
        //说明是生命周期表单
        _strwhere.append(String.format(" and A.lifenode_id = '%s' ", search.get("keyid")[0]));
      } else {
        //全权限查询只在普通动态表单生效
        boolean _hasTopAuthority = checkSelectAuthority(user, search.get("form_id")[0]);

        if (!_hasTopAuthority) {
          _strwhere.append(String.format(" and CREATED_BY = '%s'", user.getId()));
        }

      }
    }else {
      _strsql.append("SELECT A.conflict_id,A.ROW_ID,A.CREATED,A.CREATED_BY,A.CREATED_BY_NAME,A.LAST_UPD,A.LAST_UPD_BY,A.LAST_UPD_BY_NAME,A.ATTRIB_01,A.ATTRIB_02,A.ATTRIB_101,A.ATTRIB_102,A.ATTRIB_103,A.ATTRIB_104" +
              ",case when  A.ATTRIB_101='0'   then '待审核'\n" +
              "    when  A.ATTRIB_101='1'   then '审核通过'\n" +
              "\t\twhen  A.ATTRIB_101='-1'  then '不通过'\n" +
              "\t\twhen  A.ATTRIB_101='-9'  then '退回'\n" +
              "\t\twhen  A.ATTRIB_101='-2'  then '草稿'\n" +
              "else '' end ATTRIB_101_cn,A.ATTRIB_141,A.ATTRIB_142,A.ATTRIB_143,A.ATTRIB_144,A.ATTRIB_145,A.ATTRIB_99 ");

      strsql_sum.append("SELECT * FROM (SELECT uuid() conflict_id,'-' ROW_ID,'1899-12-31' CREATED,\n" +
              "        '-' CREATED_BY,'-' CREATED_BY_NAME,'1899-12-31' LAST_UPD,'-' LAST_UPD_BY,'-' LAST_UPD_BY_NAME,\n" +
              "        '-' ATTRIB_01, '-' ATTRIB_02, '-' ATTRIB_101,'-' ATTRIB_102, '1899-12-31' ATTRIB_103,'-' ATTRIB_104,'-' ATTRIB_101_cn,'-' ATTRIB_141,'-' ATTRIB_142,'-' ATTRIB_143,'-' ATTRIB_144,'-' ATTRIB_145,'-' ATTRIB_99 ");

      strsql_typesum.append("SELECT uuid() conflict_id,'-' ROW_ID,'1899-12-31' CREATED,\n" +
              "        '-' CREATED_BY,'-' CREATED_BY_NAME,'1899-12-31' LAST_UPD,'-' LAST_UPD_BY,'-' LAST_UPD_BY_NAME,\n" +
              "        '-' ATTRIB_01, '-' ATTRIB_02, '-' ATTRIB_101,'-' ATTRIB_102, '1899-12-31' ATTRIB_103,'-' ATTRIB_104,'-' ATTRIB_101_cn, '-' ATTRIB_141,'-' ATTRIB_142,'-' ATTRIB_143,'-' ATTRIB_144,'-' ATTRIB_145,'-' ATTRIB_99 ");


      if (search.get("row_id") != null) {
        _strwhere.append(String.format(" WHERE A.MODIFICATION_NUM = 0 and A.ATTRIB_01 = '%s' and A.ROW_ID = '%s' ", search.get("form_id")[0], search.get("row_id")[0]));
      } else {
        _strwhere.append(String.format(" WHERE A.MODIFICATION_NUM = 0 and A.ATTRIB_01 = '%s' ", search.get("form_id")[0]));
      }

      if (search.get("keyid") != null && search.get("keyid").length > 0 && StrKit.notBlank(search.get("keyid")[0])) {
        //说明是生命周期表单
        _strwhere.append(String.format(" and A.ATTRIB_02 = '%s' ", search.get("keyid")[0]));
      } else {
        //全权限查询只在普通动态表单生效


          boolean _hasTopAuthority = checkSelectAuthority(user, search.get("form_id")[0]);

          if (!_hasTopAuthority) {
            _strwhere.append(String.format(" and CREATED_BY = '%s'", user.getId()));
          }


      }
    }



    List<FormField> _fields = getFormFieldByFormid(search.get("form_id")[0]);

    if (_fields == null || _fields.size() == 0) {
      return;
    }

    for (FormField _f : _fields) {

      String __sql = "";

      _strsql_col.append(",A." + _f.getField());

      if (WhetherEnumCls.YES.getValue().equalsIgnoreCase(_f.getIsSum())) {

        strsql_sumcol.append(",sum(A." + _f.getField() + ") " + _f.getField());
        sqlStringFactroy.setIfTotal(true);
      } else {
        strsql_sumcol.append(",'-' " + _f.getField());
      }
      /**
       * 分类汇总
       */
      if (WhetherEnumCls.YES.getValue().equalsIgnoreCase(_f.getIsTypeSum())) {

        strsql_typesumcol.append(",A." + _f.getField());

        typesumcol = _f.getField();
        sqlStringFactroy.setTypeTotal(true);
      } else {

        if (WhetherEnumCls.YES.getValue().equalsIgnoreCase(_f.getIsSum())) {

          strsql_typesumcol.append(",sum(A." + _f.getField() + ") " + _f.getField());
        } else {
          strsql_typesumcol.append(",'-' " + _f.getField());
        }
      }

      if (StrKit.notBlank(_f.getCodeResource())) {
        //SELECT * FROM TS_CODE WHERE LEAF = ? AND CODETYPE = ? AND ENABLED = 1  AND  ROOTCUSTOMID = 'BUSINESS'
        char _astable = (char) _CodeTableAS;

        String _showname = _f.getField() + "_cn";

        strsql_sumcol.append(",'-' " + _showname);
        strsql_typesumcol.append(",'-' " + _showname);

        if (StrKit.notBlank(_f.getGridShowName())) {
          _showname = _f.getGridShowName();
        }

        _strsql_col.append("," + _astable + ".CODENAME " + _showname);
        _strsql_leftJoin.append(String.format(" LEFT JOIN  TS_CODE " + _astable + " ON " + _astable + ".CUSTOMID=A." + _f.getField() + " AND " + _astable + ".LEAF = '%s' AND " + _astable + ".CODETYPE = '%s' " +
                "AND " + _astable + ".ENABLED = 1  AND  " + _astable + ".ROOTCUSTOMID = 'BUSINESS' ", _f.getCodeLeaf(), _f.getCodeType()));
        _CodeTableAS++;

        if ("1".equals(_f.getIsExport())) {
          _exportCol.add(_showname);
          _exportHead.add(_f.getTitle());
        }

      } else {
        if ("1".equals(_f.getIsExport())) {
          _exportCol.add(_f.getField());
          _exportHead.add(_f.getTitle());
        }
      }

      if ("1".equals(_f.getIsSearch()) && search.get(_f.getField().toLowerCase()) != null && search.get(_f.getField().toLowerCase()).length > 0 && StrKit.notBlank(search.get(_f.getField().toLowerCase())[0])) {
        if ("datepicker".equals(_f.getType())) {
          if (search.containsKey(_f.getField() + "_and") && search.get(_f.getField() + "_and".toLowerCase())[0] != null && !"".equals(search.get(_f.getField() + "_and".toLowerCase())[0])) {

            _strwhere.append(String.format(" and A.%s <=str_to_date('%s','%%Y-%%m-%%d') ", _f.getField(), search.get(_f.getField() + "_and".toLowerCase())[0]));
          }

          _strwhere.append(String.format(" and A.%s >= str_to_date('%s','%%Y-%%m-%%d')", _f.getField(), search.get(_f.getField().toLowerCase())[0]));


        } else {
          _strwhere.append(String.format(" and A.%s like '%%%s%%' ", _f.getField(), search.get(_f.getField().toLowerCase())[0]));
        }

      }

    }

    /**
     * 审核权限  检查表单是否设置有审核流程
     */
    List<FnFormDataRole> fnFormDataRoles = FnFormDataRole.dao.find("select * from fn_form_data_role where row_id = ? and attrib_01 = ?", search.get("form_id")[0], FormDataRoleType.Audit.getValue());
    if (null != fnFormDataRoles && fnFormDataRoles.size() > 0) {

      List<String> roleCodes = user.get(AuthuserRes.KEY_ROLES);
      if (null != roleCodes && roleCodes.size() > 0) {

        String code = Db.queryStr("select code from fn_form where id = ?", search.get("form_id")[0]);
        /**
         * 大类审核
         */
        if (roleCodes.contains(TsCodeRes.BIG_AUDIT)) {

          Record record = Db.findFirst("select attrib_05 from fn_form_data a,fn_form b where a.attrib_01 = b.id and a.modification_num = 0 and b.code = 'flsp' and a.attrib_03 = ? and a.attrib_04 = ?", user.getLoginId(), code);
          if (null != record) {

            _strwhere.append(String.format(" and a.attrib_151 = '%s'", record.getStr("attrib_05")));
          }
        }
        /**
         * 中类审核
         */
        if (roleCodes.contains(TsCodeRes.MID_AUDIT)) {

          Record record = Db.findFirst("select attrib_05,attrib_06 from fn_form_data a,fn_form b where a.attrib_01 = b.id and a.modification_num = 0 and b.code = 'flsp' and a.attrib_03 = ? and a.attrib_04 = ?", user.getLoginId(), code);
          if (null != record) {

            _strwhere.append(String.format(" and a.attrib_151 = '%s' and a.attrib_152 = '%s'", record.getStr("attrib_05"), record.getStr("attrib_06")));
          }
        }
        /**
         * 小类审核
         */
        if (roleCodes.contains(TsCodeRes.SML_AUDIT)) {

          Record record = Db.findFirst("select attrib_05,attrib_06,attrib_07 from fn_form_data a,fn_form b where a.attrib_01 = b.id and a.modification_num = 0 and b.code = 'flsp' and a.attrib_03 = ? and a.attrib_04 = ?", user.getLoginId(), code);
          if (null != record) {

            _strwhere.append(String.format(" and a.attrib_151 = '%s' and a.attrib_152 = '%s' and a.attrib_153 = '%s'", record.getStr("attrib_05"), record.getStr("attrib_06"), record.getStr("attrib_07")));
          }
        }

        /**
         * 一级审核
         */
        if (roleCodes.contains(FormDataRoleType.one.getValue())) {

          _strwhere.append(String.format(" and a.attrib_141 in ('%s', '%s')", AuditStatusEnumCls.S.getValue(), AuditStatusEnumCls.Y.getValue()));
        }
        /**
         * 二级审核
         */
        if (roleCodes.contains(FormDataRoleType.two.getValue())) {
          _strwhere.append(String.format(" and a.attrib_141 = '%s' and a.attrib_142 in ('%s', '%s')", AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.S.getValue()));
        }
        /**
         * 三级审核
         */
        if (roleCodes.contains(FormDataRoleType.three.getValue())) {

          _strwhere.append(String.format(" and a.attrib_141 = '%s' and a.attrib_142 = '%s' and a.attrib_143 in ('%s', '%s')", AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.S.getValue()));
        }
        /**
         * 四级审核
         */
        if (roleCodes.contains(FormDataRoleType.four.getValue())) {

          _strwhere.append(String.format(" and a.attrib_141 = '%s' and a.attrib_142 = '%s' and a.attrib_143 = '%s' and a.attrib_144 in ('%s', '%s')", AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.S.getValue()));
        }
        /**
         * 五级审核
         */
        if (roleCodes.contains(FormDataRoleType.five.getValue())) {

          _strwhere.append(String.format(" and a.attrib_141 = '%s' and a.attrib_142 = '%s' and a.attrib_143 = '%s' and a.attrib_144 = '%s' and a.attrib_145 in ('%s', '%s')", AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.Y.getValue(), AuditStatusEnumCls.S.getValue()));
        }
      }
    }




    if(form!=null && StrKit.notBlank(form.getModel())) {
      _strsql.append(_strsql_col.toString()).append(String.format(",'-' total FROM %s A",form.getModel())).append(_strsql_leftJoin.toString()).append(_strwhere.toString());

    }else {
      _strsql.append(_strsql_col.toString()).append(",'-' total FROM FN_FORM_DATA A").append(_strsql_leftJoin.toString()).append(_strwhere.toString());
    }




    /**
     * 分类汇总
     */
    if (sqlStringFactroy.isIfTotal() && sqlStringFactroy.isTypeTotal()) {

      _strsql.append(" order by " + typesumcol + ", created");
      if(form!=null && StrKit.notBlank(form.getModel())) {
        strsql_sum.append(strsql_sumcol.toString()).append(String.format(", '总汇总' total %s A",form.getModel())).append(_strwhere.toString())
                .append(" union all ").append(strsql_typesum.append(strsql_typesumcol.toString()).append("," + typesumcol + String.format(" total FROM FN_FORM_DATA A",_strwhere.toString())).append(_strwhere.toString()).append(" group by " + typesumcol).append(" union all ").append(_strsql).append(" ) t"));

      }
      else {
        strsql_sum.append(strsql_sumcol.toString()).append(", '总汇总' total FROM FN_FORM_DATA A").append(_strwhere.toString())
                .append(" union all ").append(strsql_typesum.append(strsql_typesumcol.toString()).append("," + typesumcol + " total FROM FN_FORM_DATA A").append(_strwhere.toString()).append(" group by " + typesumcol).append(" union all ").append(_strsql).append(" ) t"));
      }
    } else if (sqlStringFactroy.isIfTotal() && !sqlStringFactroy.isTypeTotal()) {
      if(search.get("ddrqpx")!=null && StrKit.notBlank(search.get("ddrqpx")[0].toString())){
        String ddrqpx=search.get("ddrqpx")[0];
        if(ddrqpx.equals("desc")){
          _strsql.append(String.format(" order by TRIM(REPLACE(LOWER(ATTRIB_101), '-', '')),STR_TO_DATE(attrib_37,'%s') desc","%Y-%m-%d%H:%i:%s"));
        }else{
          _strsql.append(String.format(" order by TRIM(REPLACE(LOWER(ATTRIB_101), '-', '')),STR_TO_DATE(attrib_37,'%s') ","%Y-%m-%d%H:%i:%s"));
        }

      }else
        _strsql.append(" order by created");
      if(form!=null && StrKit.notBlank(form.getModel())) {
        strsql_sum.append(strsql_sumcol.toString()).append(String.format(", '总汇总' total %s A",form.getModel())).append(_strwhere.toString())
                .append(" union all ").append(_strsql).append(" ) t");
      }
      else {
        strsql_sum.append(strsql_sumcol.toString()).append(", '总汇总' total FROM FN_FORM_DATA A").append(_strwhere.toString())
                .append(" union all ").append(_strsql).append(" ) t");
      }
    } else {

      if(search.get("ddrqpx")!=null && StrKit.notBlank(search.get("ddrqpx")[0].toString())){
        String ddrqpx=search.get("ddrqpx")[0];
        if(ddrqpx.equals("desc")){
          _strsql.append(String.format(" order by TRIM(REPLACE(LOWER(ATTRIB_101), '-', '')),STR_TO_DATE(attrib_37,'%s') desc","%Y-%m-%d%H:%i:%s"));
        }else{
          _strsql.append(String.format(" order by TRIM(REPLACE(LOWER(ATTRIB_101), '-', '')),STR_TO_DATE(attrib_37,'%s') ","%Y-%m-%d%H:%i:%s"));
        }

      }else

        _strsql.append(" order by LAST_UPD desc");
    }

    if (_exportCol.size() > 0) {
      sqlStringFactroy.setColnum(_exportCol.toArray(new String[_exportCol.size()]));
    }

    if (_exportHead.size() > 0) {
      sqlStringFactroy.setHead(_exportHead.toArray(new String[_exportHead.size()]));
    }

    if ((sqlStringFactroy.isIfTotal() || sqlStringFactroy.isTypeTotal()) && search.get("row_id") == null) {

      sqlStringFactroy.setSqlExecute(strsql_sum.toString());
    } else {

      sqlStringFactroy.setSqlExecute(_strsql.toString());
    }
  }



  /**
  * @MethodName: getFormData
  * @Description: 获取动态表单数据
  * @param: search
   * @param: user
   * @param: pg
   * @param: dwkxzh
   * @param: cid
  * @return * @return rapid.jfinal.Pagination
  * @throws
  * @date 2023/8/31 13:50
  * @author wj
  */
  public Pagination getFormData(Map<String, String[]> search, Authuser user, Pagination pg, String cid) {

    SqlStringFactroy _ssf = new SqlStringFactroy(false);

    sqlStringFactroy(search, _ssf, user, cid);

    if (StrKit.isBlank(_ssf.getSqlExecute())) {
      return null;
    }

    SqlPara sqlPara = Db.getSqlParaByString(_ssf.getSqlExecute());
    if (pg.isEnabled()) {
      Page p = Db.paginate(pg.getPageIndex(), pg.getPageSize(), sqlPara);
      if (p.getList().size() > 0) {

        for (Record record : (List<Record>) p.getList()) {

          if (!StrKit.isBlank(record.getStr("created")) && record.getStr("created").startsWith("1899-12-31")) {
            record.set("created", "-");
          }

          if (!StrKit.isBlank(record.getStr("last_upd")) && record.getStr("last_upd").startsWith("1899-12-31")) {
            record.set("last_upd", "-");
          }

          if (!StrKit.isBlank(record.getStr("attrib_103")) && record.getStr("attrib_103").startsWith("1899-12-31")) {
            record.set("attrib_103", "-");
          }
        }
      }
      pg.bind(p);
    } else {

      Page p = Db.paginate(1, 999999999, sqlPara);

      if (p.getList().size() > 0) {

        for (Record record : (List<Record>) p.getList()) {

          if (!StrKit.isBlank(record.getStr("created")) && record.getStr("created").startsWith("1899-12-31")) {
            record.set("created", "-");
          }

          if (!StrKit.isBlank(record.getStr("last_upd")) && record.getStr("last_upd").startsWith("1899-12-31")) {
            record.set("last_upd", "-");
          }

          if (!StrKit.isBlank(record.getStr("attrib_103")) && record.getStr("attrib_103").startsWith("1899-12-31")) {
            record.set("attrib_103", "-");
          }
        }
      }
      pg.bind(p);
    }
    return pg;

  }

  /**
  * @MethodName: getFormDataUpdateBackup
  * @Description: 获取动态表单数据
  * @param: search
   * @param: user
   * @param: pg
   * @param: dwkxzh
   * @param: cid
  * @return * @return rapid.jfinal.Pagination
  * @throws
  * @date 2023/8/31 13:51
  * @author wj
  */
  public Pagination getFormDataUpdateBackup(Map<String, String[]> search, Authuser user, Pagination pg, String cid) {

    SqlStringFactroy _ssf = new SqlStringFactroy(false);

    sqlStringFactroy(search, _ssf, user,cid);

    if (StrKit.isBlank(_ssf.getSqlExecute())) {
      return null;
    }

    SqlPara sqlPara = Db.getSqlParaByString(_ssf.getSqlExecute());
    if (pg.isEnabled()) {
      Page p = Db.paginate(pg.getPageIndex(), pg.getPageSize(), sqlPara);
      pg.bind(p);
    } else {
      Page p = Db.paginate(1, 999999999, sqlPara);
      pg.bind(p);
    }
    return pg;

  }

  /**
  * @MethodName: export
  * @Description: 导出
  * @param: search
   * @param: user
   * @param: dwkxzh
   * @param: cid
  * @return * @return net.yxsoft.bean.FormDataExportFactroy
  * @throws
  * @date 2023/8/31 13:51
  * @author wj
  */
  public FormDataExportFactroy export(Map<String, String[]> search, Authuser user, String cid) {

    FormDataExportFactroy _returnData = new FormDataExportFactroy();

    List<Record> _data = new ArrayList<Record>();

    SqlStringFactroy _ssf = new SqlStringFactroy(false);

    sqlStringFactroy(search, _ssf, user, cid);

    if (StrKit.isBlank(_ssf.getSqlExecute())) {

      return null;
    }

    _data = Db.find(_ssf.getSqlExecute());

    Record _form = Db.findFirst("select * from fn_form where id = ?", search.get("attrib_01")[0]);

    if (_form != null) {
      _returnData.setFilename(_form.getStr("name"));
    }

    _returnData.setData(_data);
    _returnData.setColnum(_ssf.getColnum());
    _returnData.setHead(_ssf.getHead());
    return _returnData;
  }


  /**
  * @MethodName: add
  * @Description: 保存
  * @param: obj
   * @param: user
   * @param: formType
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:51
  * @author wj
  */
  public TResult add(FnFormData obj, Authuser user, String formType,String formid,String lifenodeid) throws ParseException {
    if (obj == null) {
      return fail();
    }
    String _now = ToolDateTime.format(ToolDateTime.getDate(), "yyyy-MM-dd hh:mm:ss");
    Form form =Form.dao.findById(formid);


    Record record=new Record();

    String cid=Helper.bulidUUID();
    if(form!=null && StrKit.notBlank(form.getModel())){
      record.setColumns(obj);
      record.set("modification_num",0);
      record.set("conflict_id",cid);
      record.set("form_id",formid);
      record.set("lifenode_id",lifenodeid);


      record.set("created",ToolDateTime.getDate());
      record.set("created_by",user.getId());
      record.set("created_by_name",user.getName());
      record.set("last_upd",ToolDateTime.getDate());
      record.set("last_upd_by",user.getId());
      record.set("last_upd_by_name",user.getName());

    }
    List<FormField> _fields =null;
    if(form!=null && StrKit.notBlank(form.getModel())) {
      _fields = getFormFieldByFormid(formid);
    }else{
      _fields = getFormFieldByFormid(formid);
    }
    if (_fields == null || _fields.size() == 0) {
      return TResult.fail().msg("动态表单字段数据不存在。");
    }




    String _state = AuditStatusEnumCls.Draft.getValue();

    if ("0".equals(formType)) {
      //生命周期表单
      if(form!=null && StrKit.notBlank(form.getModel())){
        record.set("created_by",obj.getCreatedBy());
        record.set("audit_state",AuditStatusEnumCls.ToAudit.getValue());
        TResult _r = checkOperationLimits_model(record, "add", user);

        if (_r.isFail()) {
          return _r;
        }
      }else {
        obj.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
        TResult _r = checkOperationLimits(obj, "add", user);

        if (_r.isFail()) {
          return _r;
        }
      }
      _state = AuditStatusEnumCls.ToAudit.getValue();
    }
    for (FormField _f : _fields) {

      if ("1".equals(_f.getDataOnly())) {
        TResult rs=null;
        if(form!=null && StrKit.notBlank(form.getModel())) {
          rs = checkDulpicate_model(null, _f.getTitle(), _f.getField(), record.getStr(_f.getField()), lifenodeid,form.getModel());
        }else{
          rs = checkDulpicate(null, obj.getAttrib01(), _f.getTitle(), _f.getField(), obj.getStr(_f.getField()), obj.getAttrib02());

        }
        if (rs.isFail()) {
          return rs;
        }
      }

      /**
       * 自动编码
       */
      if(WhetherEnumCls.YES.getValue().equals(_f.getIsAutocode())){
        if(form!=null && StrKit.notBlank(form.getModel())) {
          record.set(_f.getField().toLowerCase(), getAutocode(_f));
        }else
          obj.set(_f.getField().toLowerCase(), getAutocode(_f));
      }
    }
    if (com.jfinal.kit.StrKit.isBlank(obj.getAttrib101())) {
      if(form!=null && StrKit.notBlank(form.getModel())) {
        record.set("audit_state",_state);
      }else
        obj.setAttrib101(_state);

    }

    String formId = Db.queryStr("select id from fn_form where code = 'appManager'");
    if(StrKit.notBlank(formId) && formId.equals(obj.getAttrib01())){

      obj.setAttrib04(HashKit.md5(obj.getAttrib03()));
      obj.setAttrib05(HashKit.sha256(obj.getAttrib03()));
    }

    obj.setCreated(ToolDateTime.getDate());
    obj.setCreatedBy(user.getId());
    obj.setCreatedByName(user.getName());
    obj.setLastUpd(ToolDateTime.getDate());
    obj.setLastUpdBy(user.getId());
    obj.setLastUpdByName(user.getName());


    if(form!=null && StrKit.notBlank(form.getModel())) {
      TResult result= CustomDb.saveWithExceptionHandling(form.getModel(),record);
      if (result.isSuccess()) {


        Form from = Form.dao.findFirst("select * from fn_form where id = ?", formid);
        if (StrKit.notBlank(from.getBlockChainMode()) && from.getBlockChainMode().equals("cfsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name=? and a.attrib_name  in (select field from fn_form_field where form_id =?)  " +
                  "        order by a.id", form.getModel(),formid);

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";
          }
          SnowFlakeIdUtil generator = new SnowFlakeIdUtil(1L); // 设置workerId为1
          int cuid=generator.generateUniqueInt();
          Record record1=Db.findFirst("select conflict_id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "audit_state from "+form.getModel()+" where modification_num=0 and conflict_id=?", cid);
          String attrStr = QuorumKit.attrStrM(record1);
          String hashValue = QuorumKit.encodeCreate_new("createModel",  BigInteger.valueOf(cuid),  BigInteger.valueOf(cuid),  BigInteger.valueOf(cuid), BigInteger.valueOf(record1.getDate("created").getTime() / 1000).toString(), record1.getStr("created_by")==null?"":record1.getStr("created_by"), BigInteger.valueOf(record1.getDate("last_upd") == null ? record1.getDate("created").getTime() : record1.getDate("last_upd").getTime() / 1000).toString(), record1.getStr("last_upd_by") == null ? record1.getStr("created_by") : record1.getStr("last_upd_by") , BigInteger.valueOf(0), form.getModel(), attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          record1.set("hash_val",txHash);
            result=  CustomDb.updateWithExceptionHandling(form.getModel(),"conflict_id",record1);
        }
      }
     return result;
    }else {

      if (obj.save()) {


        Form from = Form.dao.findFirst("select * from fn_form where id = ?", formid);
        if (StrKit.notBlank(from.getBlockChainMode()) && from.getBlockChainMode().equals("cfsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name='fn_form_data' and a.attrib_name  in (select field from fn_form_field where form_id =?) and a.attrib_name not in ('attrib_01','attrib_02','attrib_101','attrib_102','attrib_103','attrib_104','attrib_99') " +
                  "        order by a.id",formid);

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";

          }
          FnFormData fn = FnFormData.dao.findFirst("select conflict_id,id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "attrib_01,attrib_02,attrib_101,attrib_102,attrib_103,attrib_104 from fn_form_data where modification_num=0 and conflict_id=?", obj.getConflictId());
          String attrStr = QuorumKit.attrStr(fn);
          String hashValue = QuorumKit.encodeCreate("createModel", BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getCreated().getTime() / 1000), fn.getCreatedBy(), BigInteger.valueOf(fn.getLastUpd() == null ? fn.getCreated().getTime() : fn.getLastUpd().getTime() / 1000), fn.getLastUpdBy() == null ? fn.getCreatedBy() : fn.getLastUpdBy(), BigInteger.valueOf(0), "fn_form_data", attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          fn.setAttrib99(txHash);
          fn.update();
        }
        return success();
      } else {
        return fail();
      }
    }



  }


  /**
  * @MethodName: update
  * @Description: 修改
  * @param: obj
   * @param: user
   * @param: formType
   * @param: userType
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:52
  * @author wj
  */
  public TResult update(FnFormData obj, Authuser user, String formType, String userType,String formid,String lifenodeid) throws ParseException {

    if (obj == null) {
      return fail();
    }

    List<FormField> _fields = getFormFieldByFormid(formid);
    Form form =Form.dao.findById(formid);
    if (_fields == null || _fields.size() == 0) {
      return TResult.fail().msg("动态表单字段数据不存在。");
    }

    FnFormData _old = dao.findById(obj.getConflictId());
    Record _oldrecord=null;
    if(form!=null && StrKit.notBlank(form.getModel())) {

      _oldrecord = Db.findFirst("select * from " + form.getModel() + " where conflict_id=?", obj.getConflictId());
    }
    for (FormField field : _fields) {

      if (TsCodeRes.PLTYPE.equals(field.getType())) {

        if (StrKit.isBlank(obj.getStr(field.getField()))) {
          if(form!=null && StrKit.notBlank(form.getModel())) {
            obj.set(field.getField(), _oldrecord.get(field.getField()));
          }else {
            obj.set(field.getField(), _old.get(field.getField()));
          }
        }
      }
    }
    if(form!=null && StrKit.notBlank(form.getModel())) {
      if (_oldrecord == null) {
        return TResult.fail().msg("记录不存在或已被删除。");
      }
    }
    else{
      if (_old == null) {
        return TResult.fail().msg("记录不存在或已被删除。");
      }
    }

    String _state = AuditStatusEnumCls.Draft.getValue();

    if ("0".equals(formType)) {


      if(form!=null && StrKit.notBlank(form.getModel())){

        TResult _r = checkOperationLimits_model(_oldrecord, "add", user);

        if (_r.isFail()) {
          return _r;
        }
      }else {
        //生命周期表单
        TResult _r = checkOperationLimits(_old, "update", user);
        if (_r.isFail()) {
          return _r;
        }
      }
      _state = AuditStatusEnumCls.ToAudit.getValue();
    } else {

      if (StrKit.isBlank(userType)) {

        return TResult.fail().msg("没有相关权限。");
      }


      if (userType.toUpperCase().equals(FormDataRoleType.Audit.getValue())) {
        //普通表单，保存如果是审核人，就要复制一条数据，MODIFICATION_NUM=-1，直接通过

        if(form!=null && StrKit.notBlank(form.getModel())) {
          Record _newrecord=new Record();
          String cid=Helper.bulidUUID();
          _newrecord.setColumns(_oldrecord);
          _newrecord.set("conflict_id",cid);
          _newrecord.set("row_id",null);
          _newrecord.set("par_row_id",_oldrecord.get("par_row_id"));
          _newrecord.set("created_by",ToolDateTime.getDate());
          _newrecord.set("created_by",user.getId());
          _newrecord.set("last_upd",ToolDateTime.getDate());
          _newrecord.set("last_upd_by",user.getId());
          _newrecord.set("modification_num",new BigDecimal(-1));
          _oldrecord.set("audit_state",AuditStatusEnumCls.Pass.getValue());
          _oldrecord.set("audit_date",ToolDateTime.getDate());
          _oldrecord.set("audit_by",user.getId());
          _oldrecord.set("audit_by_name",user.getName());
          Db.save(form.getModel(),_newrecord);
        }else {
          FnFormData _new = new FnFormData();
          //region 复制保存审核前数据
          _new._setAttrs(_old);
          _new.setConflictId(null);
          _new.setRowId(null);
          _new.setParRowId(_old.getRowId());
          _new.setCreated(ToolDateTime.getDate());
          _new.setCreatedBy(user.getId());
          _new.setCreatedByName(user.getName());
          _new.setLastUpd(ToolDateTime.getDate());
          _new.setLastUpdBy(user.getId());
          _new.setLastUpdByName(user.getName());
          _new.setModificationNum(new BigDecimal(-1));
          _old.setAttrib101(AuditStatusEnumCls.Pass.getValue());
          _old.setAttrib102(user.getId());
          _old.setAttrib103(ToolDateTime.getDate());
          _old.setAttrib104(user.getName());
          _new.save();
        }




        //endregion
      } else {

        if(form!=null && StrKit.notBlank(form.getModel())) {
          if (AuditStatusEnumCls.ToAudit.getValue().equals(_oldrecord.get("audit_state"))) {
            return TResult.fail().msg("当前数据已提交，不可修改。");
          }

          if (AuditStatusEnumCls.Pass.getValue().equals(_oldrecord.get("audit_state"))) {
            return TResult.fail().msg("当前数据已审核通过，不可修改。");
          }

          if (com.jfinal.kit.StrKit.isBlank(_oldrecord.getStr("audit_state"))) {
            _oldrecord.set("audit_state",AuditStatusEnumCls.Draft.getValue());
          }
        }
        else {
          if (AuditStatusEnumCls.ToAudit.getValue().equals(_old.getAttrib101())) {
            return TResult.fail().msg("当前数据已提交，不可修改。");
          }

          if (AuditStatusEnumCls.Pass.getValue().equals(_old.getAttrib101())) {
            return TResult.fail().msg("当前数据已审核通过，不可修改。");
          }

          if (com.jfinal.kit.StrKit.isBlank(obj.getAttrib101())) {
            _old.setAttrib101(AuditStatusEnumCls.Draft.getValue());
          }
        }

      }
    }


    for (FormField _f : _fields) {


      if ("1".equals(_f.getDataOnly())) {
        TResult rs=null;
        if(form!=null && StrKit.notBlank(form.getModel())) {
          rs = checkDulpicate_model(null, _f.getTitle(), _f.getField(), _oldrecord.getStr(_f.getField()), lifenodeid,form.getModel());
        }else{
          rs = checkDulpicate(null, obj.getAttrib01(), _f.getTitle(), _f.getField(), obj.getStr(_f.getField()), obj.getAttrib02());

        }
        if (rs.isFail()) {
          return rs;
        }
      }

      /**
       * 自动编码
       */
      if(WhetherEnumCls.YES.getValue().equals(_f.getIsAutocode())){
        if(form!=null && StrKit.notBlank(form.getModel())) {
          _oldrecord.set(_f.getField().toLowerCase(), getAutocode(_f));
        }else
          obj.set(_f.getField().toLowerCase(), getAutocode(_f));
      }


    }



    //endregion

    if(form!=null && StrKit.notBlank(form.getModel())) {
      //region 字段属性赋值
      _oldrecord.setColumns(obj);
      _oldrecord.set("last_upd",ToolDateTime.getDate());
      _oldrecord.set("last_upd_by",user.getId());

      TResult result= CustomDb.saveWithExceptionHandling(form.getModel(),"conflict_id",_oldrecord);
      if (result.isSuccess()) {

        Form from = Form.dao.findFirst("select * from fn_form where id = ?", formid);
        if (StrKit.notBlank(from.getBlockChainMode()) && from.getBlockChainMode().equals("cfsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name=? and a.attrib_name  in (select field from fn_form_field where form_id =?)  " +
                  "        order by a.id", form.getModel(),formid);

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";

          }
          Record record1=Db.findFirst("select conflict_id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "audit_state from "+form.getModel()+" where modification_num=0 and conflict_id=?",obj.getConflictId());
          String attrStr = QuorumKit.attrStrM(record1);
          String hashValue = QuorumKit.encodeCreate("createModel", Helper.bulidUUIDBigInteger(), Helper.bulidUUIDBigInteger(), Helper.bulidUUIDBigInteger(), BigInteger.valueOf(record1.getDate("created").getTime() / 1000), record1.getStr("created_by")==null?"":record1.getStr("created_by"), BigInteger.valueOf(record1.getDate("last_upd") == null ? record1.getDate("created").getTime() : record1.getDate("last_upd").getTime() / 1000), record1.getStr("last_upd_by") == null ? record1.getStr("created_by") : record1.getStr("last_upd_by") , BigInteger.valueOf(0), form.getModel(), attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          record1.set("hash_val",txHash);
          result= CustomDb.updateWithExceptionHandling(form.getModel(),"conflict_id",record1);
        }

      }
        return result;

    }else {
      //region 字段属性赋值
      _old._setAttrs(obj);
      _old.setLastUpd(ToolDateTime.getDate());
      _old.setLastUpdBy(user.getId());
      _old.setLastUpdByName(user.getName());
      if(_old.update()) {
        Form from = Form.dao.findFirst("select * from fn_form where id = ?", formid);
        if (StrKit.notBlank(from.getBlockChainMode()) && from.getBlockChainMode().equals("cfsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name='fn_form_data' and a.attrib_name  in (select field from fn_form_field where form_id =?) and a.attrib_name not in ('attrib_01','attrib_02','attrib_101','attrib_102','attrib_103','attrib_104','attrib_99') " +
                  "        order by a.id", formid);

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";

          }

          FnFormData fn = FnFormData.dao.findFirst("select conflict_id,id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "attrib_01,attrib_02,attrib_101,attrib_102,attrib_103,attrib_104 from fn_form_data where modification_num=0 and conflict_id=?", obj.getConflictId());
          String attrStr = QuorumKit.attrStr(fn);
          String hashValue = QuorumKit.encodeCreate("createModel", BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getCreated().getTime() / 1000), fn.getCreatedBy(), BigInteger.valueOf(fn.getLastUpd() == null ? fn.getCreated().getTime() : fn.getLastUpd().getTime() / 1000), fn.getLastUpdBy() == null ? fn.getCreatedBy() : fn.getLastUpdBy(), BigInteger.valueOf(0), "fn_form_data", attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          fn.setAttrib99(txHash);
          fn.update();
        }

        return success();
      }else {
        return fail();
      }
    }
  }

  /**
  * @MethodName: getParentForms
  * @Description:
  * @param:
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 13:53
  * @author wj
  */
  public List<Record> getParentForms() {

    return Db.find("select id,name from fn_form where type = 1 and parentid is null  order by code");
  }

  /**
  * @MethodName: remove
  * @Description: 删除
  * @param: ids
   * @param: user
   * @param: formType
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:53
  * @author wj
  */
  public TResult remove(String ids, Authuser user, String formType,String fomrid) throws ParseException {
    if (StrKit.isBlank(ids)) {
      return fail();
    }


    Form form =Form.dao.findById(fomrid);



    String[] _ids = ids.split(",");
    try {
      for (int i = 0; i < _ids.length; i++) {
        if(form!=null && StrKit.notBlank(form.getModel())) {
          Record record=Db.findFirst("select * from "+form.getModel()+" where conflict_id=?",_ids[i]);
          if (record == null) {
            return TResult.fail().msg("记录不存在或已被删除。");
          }
          if (AuditStatusEnumCls.ToAudit.getValue().equals(record.get("audit_state")) || AuditStatusEnumCls.Pass.getValue().equals(record.get("audit_state"))) {
            return TResult.fail().msg("要删除的记录中存在待审核或审核通过的记录。");
          }
          if ("0".equals(formType)) {
            //生命周期表单
            TResult _r = checkOperationLimits_model(record, "remove", user);
            if (_r.isFail()) {
              return _r;
            }
          }
          Db.delete(form.getModel(),"conflict_id",record);
        }else {
          FnFormData old = dao.findById(_ids[i]);

          if (old == null) {
            return TResult.fail().msg("记录不存在或已被删除。");
          }

          if (AuditStatusEnumCls.ToAudit.getValue().equals(old.getAttrib101()) || AuditStatusEnumCls.Pass.getValue().equals(old.getAttrib101())) {
            return TResult.fail().msg("要删除的记录中存在待审核或审核通过的记录。");
          }

          if ("0".equals(formType)) {
            //生命周期表单
            TResult _r = checkOperationLimits(old, "remove", user);
            if (_r.isFail()) {
              return _r;
            }
          }

          dao.deleteById(_ids[i]);
        }
      }
    } catch (Exception ex) {
      return fail();
    }

    return success();
  }


  /**
  * @MethodName: checkOperationLimits
  * @Description: 验证操作权限
  * @param: old
   * @param: operation
   * @param: user
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:53
  * @author wj
  */
  public TResult checkOperationLimits(FnFormData old, String operation, Authuser user) throws ParseException {
    if (!"add".equals(operation)) {
      if (!old.getCreatedBy().equals(user.getId())) {
        return TResult.fail().msg("只能操作当前用户新增数据。");
      }

      if (AuditStatusEnumCls.Pass.getValue().equals(old.getAttrib101())) {
        return TResult.fail().msg("当前提交数据已经审核，不可再操作。");
      }
    }

    TResult _r = CheckNodeIsTimeOut(old.getAttrib02());
    if (_r.isFail()) {
      return _r;
    }

    return success();
  }

  /**
  * @MethodName: checkOperationLimits
  * @Description: 验证操作权限
  * @param: ids
   * @param: operation
   * @param: user
   * @param: nodeid
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:53
  * @author wj
  */
  public TResult checkOperationLimits(String ids, String operation, Authuser user, String nodeid) throws ParseException {

    if (StrKit.isBlank(ids)) {
      FnFormData _model = new FnFormData();
      _model.setAttrib02(nodeid);
      //生命周期表单
      TResult _r = checkOperationLimits(_model, operation, user);
      if (_r.isFail()) {
        return _r;
      }
    } else {
      String[] _ids = ids.split(",");
      try {
        for (int i = 0; i < _ids.length; i++) {

          FnFormData _old = dao.findById(_ids[i]);

          if (_old == null) {
            return TResult.fail().msg("记录不存在或已被删除。");
          }
          TResult _r = checkOperationLimits(_old, operation, user);
          if (_r.isFail()) {
            return _r;
          }
        }
      } catch (Exception ex) {
        return fail();
      }
    }

    return success();
  }




  /**
  * @MethodName: checkDulpicate
  * @Description:
  * @param: id
   * @param: formId
   * @param: title
   * @param: fieldKey
   * @param: fieldValue
   * @param: keyid
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:54
  * @author wj
  */
  public TResult checkDulpicate(String id, String formId, String title, String fieldKey, String fieldValue, String keyid) {
    FormField temp;

    if (StrKit.notBlank(keyid)) {
      if (id != null) {
        temp = FormField.dao.findFirst("select * from FN_FORM_DATA  where conflict_id <> ? and attrib_01 = ? and attrib_02 = ? and  " + fieldKey + "=?", id, formId, keyid, fieldValue);
      } else {
        temp = FormField.dao.findFirst("select * from FN_FORM_DATA  where  attrib_01 = ? and  attrib_02 = ? and  " + fieldKey + "=?", formId, keyid, fieldValue);
      }
    } else {
      if (id != null) {
        temp = FormField.dao.findFirst("select * from FN_FORM_DATA  where conflict_id <> ? and attrib_01 = ?  and  " + fieldKey + "=?", id, formId, fieldValue);
      } else {
        temp = FormField.dao.findFirst("select * from FN_FORM_DATA  where  attrib_01 = ?  and  " + fieldKey + "=?", formId, fieldValue);
      }
    }


    if (temp != null) {
      return TResult.fail().msg(title + "有重复。");
    }

    return success();
  }


  /**
  * @MethodName: audit
  * @Description:  审核
  * @param: formId
   * @param: ids
   * @param: user
   * @param: status
   * @param: opinion
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:54
  * @author wj
  */
  public TResult audit(String formId, String ids, Authuser user, String status, String opinion) {

    if (StrKit.isBlank(ids) || StrKit.isBlank(formId)) {
      return fail();
    }

    if(!AuditStatusEnumCls.COLLECTS_AUDITS.contains(status)){
      return TResult.fail().msg("非法参数。");
    }
    Form form =Form.dao.findById(formId);

    if(form!=null && StrKit.notBlank(form.getModel())) {
      Record _oldrecord =  Db.findFirst("select * from "+form.getModel()+" where conflict_id=?",ids);;
      if (null == _oldrecord) {
        return TResult.fail().msg("记录不存在或已被删除。");
      }

      Record record = rsv.getFormDataUserRole(formId, user);

      if (null == record || (!record.getStr("attrib_01").equals(FormDataRoleType.Submit.getValue())
              && !record.getStr("attrib_01").equals(FormDataRoleType.Audit.getValue()))) {

        return TResult.fail().msg("无相关权限。");
      }

      if (status.equals(AuditStatusEnumCls.ToAudit.getValue()) && record.getStr("attrib_01").equals(FormDataRoleType.Submit.getValue())) {

        if (_oldrecord.get("audit_state").equals(AuditStatusEnumCls.Pass.getValue())) {
          return TResult.fail().msg("选中的数据数据已经审核通过。");
        }

        if (_oldrecord.get("audit_state").equals(AuditStatusEnumCls.ToAudit.getValue())) {
          return TResult.fail().msg("选中的数据已经提交审核。");
        }
        _oldrecord.set("audit_state", AuditStatusEnumCls.ToAudit.getValue());
      }else {
        if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

          if (StrKit.notBlank(_oldrecord.getStr("audit_state")) && _oldrecord.get("audit_state").equals(AuditStatusEnumCls.Pass.getValue())) {
            return TResult.fail().msg("选中的数据数据已经审核通过。");
          }
          //表单整体审核通过
          _oldrecord.set("audit_state",AuditStatusEnumCls.Pass.getValue());
        } else {
          //反审核


          if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

            _oldrecord.set("audit_state",AuditStatusEnumCls.NoPass.getValue());
            if (StrKit.notBlank(opinion)) {

              //不通过原因 发系统消息
              MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formId)
                      .set("lastBy", _oldrecord.get("audit_by")).set("opinion", opinion));

            }
          } else {
            _oldrecord.set("audit_state",AuditStatusEnumCls.ToAudit.getValue());
          }
        }

        _oldrecord.set("audit_by",user.getId());
        _oldrecord.set("audit_by_name",user.getName());
        _oldrecord.set("audit_date",ToolDateTime.getDate());
      }

      TResult tResult = CustomDb.updateWithExceptionHandling(form.getModel(),"conflict_id",_oldrecord);

      if (tResult.isSuccess() &&  _oldrecord.get("audit_state").equals(AuditStatusEnumCls.Pass.getValue())) {

        if (StrKit.isBlank(form.getBlockChainMode()) || form.getBlockChainMode().equals("shsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name=? and a.attrib_name  in (select field from fn_form_field where form_id =?)  " +
                  "        order by a.id", form.getModel(),formId);

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";

          }

          Record record1=Db.findFirst("select conflict_id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "audit_state from "+form.getModel()+" where modification_num=0 and conflict_id=?",_oldrecord.getStr("conflict_id"));
          String attrStr = QuorumKit.attrStrM(record1);
          String hashValue = QuorumKit.encodeCreate("createModel", Helper.bulidUUIDBigInteger(), Helper.bulidUUIDBigInteger(), Helper.bulidUUIDBigInteger(), BigInteger.valueOf(record1.getDate("created").getTime() / 1000), record1.getStr("created_by"), BigInteger.valueOf(record1.getDate("last_upd") == null ? record1.getDate("created").getTime() : record1.getDate("last_upd").getTime() / 1000), record1.getStr("last_upd_by") == null ? record1.getStr("created_by") : record1.getStr("last_upd_by") , BigInteger.valueOf(0), form.getModel(), attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          record1.set("hash_val",txHash);
          tResult=  CustomDb.updateWithExceptionHandling(form.getModel(),"conflict_id",record1);
        }

      }

      return tResult;

    }else {
      FnFormData formData = dao.findById(ids);

      if (null == formData) {
        return TResult.fail().msg("记录不存在或已被删除。");
      }
      Form from = Form.dao.findFirst("select * from fn_form where id = ?", formData.getAttrib01());

      Record record = rsv.getFormDataUserRole(formId, user);

      if (null == record || (!record.getStr("attrib_01").equals(FormDataRoleType.Submit.getValue())
              && !record.getStr("attrib_01").equals(FormDataRoleType.Audit.getValue()))) {

        return TResult.fail().msg("无相关权限。");
      }
      /**
       * 提交
       */
      if (status.equals(AuditStatusEnumCls.ToAudit.getValue()) && record.getStr("attrib_01").equals(FormDataRoleType.Submit.getValue())) {

        if (formData.getAttrib101().equals(AuditStatusEnumCls.Pass.getValue())) {
          return TResult.fail().msg("选中的数据数据已经审核通过。");
        }

        if (formData.getAttrib101().equals(AuditStatusEnumCls.ToAudit.getValue())) {
          return TResult.fail().msg("选中的数据已经提交审核。");
        }

        List<Record> records = Db.find("select id,name,code from fn_form where parentid = ?", formData.getAttrib01());
        if (null != records && records.size() > 0) {

          String msg = "";
          for (Record red : records) {

            int n = Db.queryNumber("select count(1) from fn_form_data where modification_num = 0 and attrib_01 = ? and row_id = ?", red.getStr("id"), ids).intValue();
            if (n == 0) {
              msg += red.getStr("name") + "|";
            }
          }
          if (StrKit.notBlank(msg)) {
            return TResult.fail().msg("子模型：" + msg + " 尚未填报, 请点击 上方对应子模型按钮进行填报后，再进行提交!");
          }

          /**
           * 子模型提交
           */
          for (Record red : records) {

              CustomDb.updateWithExceptionHandling("update fn_form_data set attrib_101 = ? where row_id = ? and attrib_01 = ?", AuditStatusEnumCls.ToAudit.getValue(), ids, red.getStr("id"));
          }

        }

        formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
        formData.setAttrib141(AuditStatusEnumCls.S.getValue());
      } else {


        /**
         * 一级审核
         */
        if (record.getStr("rolecode").equals(FormDataRoleType.one.getValue())) {

          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (formData.getAttrib141().equals(AuditStatusEnumCls.Y.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            if (!formData.getAttrib141().equals(AuditStatusEnumCls.S.getValue())) {
              return TResult.fail().msg("当前数据审核状态错误。");
            }
            formData.setAttrib141(AuditStatusEnumCls.Y.getValue());
            //是否终审
            if (WhetherEnumCls.YES.getValue().equals(record.getStr("attrib_03"))) {
              //表单整体审核通过
              formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
            } else {
              formData.setAttrib142(AuditStatusEnumCls.S.getValue());
            }
          } else {

            formData.setAttrib141(AuditStatusEnumCls.N.getValue());
            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getCreatedBy()).set("opinion", opinion));
              }
            } else {
              formData.setAttrib101(AuditStatusEnumCls.Draft.getValue());
            }
          }

        }
        /**
         * 二级审核
         */
        if (record.getStr("rolecode").equals(FormDataRoleType.two.getValue())) {

          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (formData.getAttrib142().equals(AuditStatusEnumCls.Y.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            if (!formData.getAttrib142().equals(AuditStatusEnumCls.S.getValue())) {
              return TResult.fail().msg("当前数据审核状态错误。");
            }
            formData.setAttrib142(AuditStatusEnumCls.Y.getValue());
            //是否终审
            if (WhetherEnumCls.YES.getValue().equals(record.getStr("attrib_03"))) {
              //表单整体审核通过
              formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
            } else {
              formData.setAttrib143(AuditStatusEnumCls.S.getValue());
            }
          } else {
            //反审核
            formData.setAttrib141(AuditStatusEnumCls.S.getValue());
            formData.setAttrib142(AuditStatusEnumCls.N.getValue());

            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getAttrib102()).set("opinion", opinion));
              }
            } else {

              formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
            }
          }
        }
        /**
         * 三级审核
         */
        if (record.getStr("rolecode").equals(FormDataRoleType.three.getValue())) {

          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (formData.getAttrib143().equals(AuditStatusEnumCls.Y.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            if (!formData.getAttrib143().equals(AuditStatusEnumCls.S.getValue())) {
              return TResult.fail().msg("当前数据审核状态错误。");
            }

            formData.setAttrib143(AuditStatusEnumCls.Y.getValue());
            //是否终审
            if (WhetherEnumCls.YES.getValue().equals(record.getStr("attrib_03"))) {
              //表单整体审核通过
              formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
            } else {
              formData.setAttrib144(AuditStatusEnumCls.S.getValue());
            }
          } else {
            formData.setAttrib142(AuditStatusEnumCls.S.getValue());
            formData.setAttrib143(AuditStatusEnumCls.N.getValue());

            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getAttrib102()).set("opinion", opinion));
              }
            } else {
              formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
            }
          }
        }
        /**
         * 四级审核
         */
        if (record.getStr("rolecode").equals(FormDataRoleType.four.getValue())) {

          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (formData.getAttrib144().equals(AuditStatusEnumCls.Y.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            if (!formData.getAttrib144().equals(AuditStatusEnumCls.S.getValue())) {
              return TResult.fail().msg("当前数据审核状态错误。");
            }
            formData.setAttrib144(AuditStatusEnumCls.Y.getValue());
            //是否终审
            if (WhetherEnumCls.YES.getValue().equals(record.getStr("attrib_03"))) {
              //表单整体审核通过
              formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
            } else {
              formData.setAttrib145(AuditStatusEnumCls.S.getValue());
            }
          } else {
            formData.setAttrib143(AuditStatusEnumCls.S.getValue());
            formData.setAttrib144(AuditStatusEnumCls.N.getValue());


            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getAttrib102()).set("opinion", opinion));
              }
            } else {
              formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
            }
          }
        }
        /**
         * 五级审核
         */
        if (record.getStr("rolecode").equals(FormDataRoleType.five.getValue())) {

          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (formData.getAttrib145().equals(AuditStatusEnumCls.Y.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            if (!formData.getAttrib145().equals(AuditStatusEnumCls.S.getValue())) {
              return TResult.fail().msg("当前数据审核状态错误。");
            }
            formData.setAttrib145(AuditStatusEnumCls.Y.getValue());
            //表单整体审核通过
            formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
          } else {
            //反审核
            formData.setAttrib144(AuditStatusEnumCls.S.getValue());
            formData.setAttrib145(AuditStatusEnumCls.N.getValue());

            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getAttrib102()).set("opinion", opinion));
              }
            } else {
              formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
            }
          }
        } else {
          if (status.equals(AuditStatusEnumCls.Pass.getValue())) {

            if (StrKit.notBlank(formData.getAttrib101()) && formData.getAttrib101().equals(AuditStatusEnumCls.Pass.getValue())) {
              return TResult.fail().msg("选中的数据数据已经审核通过。");
            }
            //表单整体审核通过
            formData.setAttrib101(AuditStatusEnumCls.Pass.getValue());
          } else {
            //反审核


            if (status.equals(AuditStatusEnumCls.NoPass.getValue())) {

              formData.setAttrib101(AuditStatusEnumCls.NoPass.getValue());
              if (StrKit.notBlank(opinion)) {

                //不通过原因 发系统消息
                MessageKit.sendMessage(ActionRes.PUSH_MESSAGE, Kv.create().set("formId", formData.getAttrib01())
                        .set("lastBy", formData.getAttrib102()).set("opinion", opinion));

              }
            } else {
              formData.setAttrib101(AuditStatusEnumCls.ToAudit.getValue());
            }
          }
        }

        formData.setAttrib102(user.getId());
        formData.setAttrib103(ToolDateTime.getDate());
        formData.setAttrib104(user.getName());


      }

      boolean isSuccess = formData.update();

      if (isSuccess && formData.getAttrib101().equals(AuditStatusEnumCls.Pass.getValue())) {

        if (StrKit.isBlank(from.getBlockChainMode()) || from.getBlockChainMode().equals("shsl")) {
          List<Record> res = Db.find("select concat(attrib_name) name from ts_datamodel_properties a " +
                  "        inner join ts_party b on a.model_id = b.conflict_id " +
                  "        where b.name='fn_form_data' and a.attrib_name  in (select field from fn_form_field where form_id =?) and a.attrib_name not in ('attrib_01','attrib_02','attrib_101','attrib_102','attrib_103','attrib_104','attrib_99') " +
                  "        order by a.id", formData.getAttrib01());

          String sqlc = "";
          for (Record rs : res) {
            sqlc += rs.getStr("name") + ",";

          }

          /**审核上链 **/
          FnFormData fn = FnFormData.dao.findFirst("select conflict_id,id,row_id,par_row_id,created,created_by,last_upd,last_upd_by,modification_num,eim_source," + sqlc + "attrib_01,attrib_02,attrib_101,attrib_102,attrib_103,attrib_104 from fn_form_data where modification_num=0 and conflict_id=?", formData.getConflictId());

          String attrStr = QuorumKit.attrStr(fn);

          String hashValue = QuorumKit.encodeCreate("createModel", BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getId()), BigInteger.valueOf(fn.getCreated().getTime() / 1000), fn.getCreatedBy(), BigInteger.valueOf(fn.getLastUpd() == null ? fn.getCreated().getTime() : fn.getLastUpd().getTime() / 1000), fn.getLastUpdBy() == null ? fn.getCreatedBy() : fn.getLastUpdBy(), BigInteger.valueOf(0), "fn_form_data", attrStr);
          String txHash = QuorumKit.sendTransaction(hashValue, PropKit.get("quorum.fromAddress"), PropKit.get("quorum.contractAddress"), "");
          fn.setAttrib99(txHash);
          fn.update();
        }
        //修改子模型审核状态
        List<Record> records = Db.find("select id,name,code from fn_form where parentid = ?", formData.getAttrib01());
        if (null != records && records.size() > 0) {

          for (Record red : records) {

            CustomDb.updateWithExceptionHandling("update fn_form_data set attrib_101 = ? where row_id = ? and attrib_01 = ?", AuditStatusEnumCls.ToAudit.getValue(), ids, red.getStr("id"));
          }
        }

        //如果审核通过触发事件

        MessageKit.sendMessage(ActionRes.PUSH_ROLE_UP, formData);

      }

      return isSuccess ? TResult.success().msg("提交成功！") : TResult.fail().msg("提交失败");
    }
  }

  /**
  * @MethodName: getMenusDatasource
  * @Description: 创建菜单的数据源   动态表单类的菜单
  * @param:
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws
  * @date 2023/8/31 13:55
  * @author wj
  */
  public List<Record> getMenusDatasource() {
    StringBuilder _strSql = new StringBuilder();
    _strSql.append("select * from ts_menu where menu_type='DYNAMICFORM' and type='1' and enabled='1' and pid='0' order by sort_id desc");
    List<Record> _returnData = new ArrayList<Record>();
    String resultSql = _strSql.toString();
    _returnData = Db.find(resultSql);
    return _returnData;
  }

  /**
  * @MethodName: saveExampleMenu
  * @Description: 保存动态表单类菜单
  * @param: model
   * @param: exampleName
   * @param: exampleCode
   * @param: loginUser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:55
  * @author wj
  */
  public TResult saveExampleMenu(TsMenu model, String exampleName, String exampleCode, Authuser loginUser) {
    Record isExist = Db.findFirst("select id from ts_menu \n" +
            " where menu_code =? ", exampleCode);
    if (null == isExist) {
      List<Record> records = Db.find(" select max(a.code) mcode,max(a.sort_id) sortid,b.code pcode from ts_menu a\n" +
              "left join ts_menu b on \n" +
              "a.pid = b.id where a.pid=?  group by b.code", model.getPid());
      TsMenu _top_menu = TsMenu.dao.findFirst("select * from ts_menu where id=?", model.getPid());

      if (_top_menu == null) {
        return TResult.fail("动态表单首级菜单不存在！");
      }

      long _mcode = 1;
      int _sortid = 1;
      if (records.size() > 0) {
        String ms=records.get(0).getStr("mcode");
        _mcode = Long.parseLong(ms) + 1;
        _sortid = Integer.parseInt(records.get(0).getStr("sortid")) + 1;
      }


      long snum = _mcode;
      int sort = _sortid;
      String code = _top_menu.getCode() + String.format("%2d", snum).replace(" ", "0");
      model.setCode(code);
      model.setSortId(sort);
      model.setVisible(WhetherEnumCls.YES.getValue());
      model.setEnabled(WhetherEnumCls.YES.getValue());
      model.setType("2");
      model.setName(exampleName);
      model.setPath("/sysadmin/formdata/index?code=" + exampleCode);
      model.setMenuType("DYNAMICFORM");
      model.setMenuCode(exampleCode);
      if (model.save() != true) {
        return TResult.fail("保存失败！");
      }

      log(loginUser.getId(), loginUser.getName(), "基础信息/动态表单维护", "创建菜单", loginUser.getIp(), "非普通菜单编号：" + model.getMenuCode());
    } else {
      return TResult.fail("创建菜单失败，非普通菜单编号已存在！");
    }
    return success();
  }

   /**
   * @MethodName: getDataRoleList
   * @Description:
   * @param: row_id
   * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
   * @throws
   * @date 2023/8/31 13:56
   * @author wj
   */
  public List<Record> getDataRoleList(String row_id) {

    List<Record> _returnData = Db.find("select  b.conflict_id, a.id row_id, b.attrib_01,d.codename attrib_01_cn, b.attrib_02,c.name attrib_02_cn,b.attrib_03, b.attrib_11,b.attrib_15 from fn_form a " +
            "INNER join fn_form_data_role b on a.id= b.row_id " +
            "left join ts_role c on c.id = b.attrib_02 " +
            "left join ts_code d on d.rootcustomid='BUSINESS' and d.codetype='FORM_DATA_ROLE_TYPE' and d.leaf='2' and b.attrib_01 = d.customid " +
            "where a.id=?", row_id);
    return _returnData;
  }


  /**
  * @MethodName: getFormsFieldsbyLifeID
  * @Description: 根据项目id获取所有字信息
  * @param: conflict_id
   * @param: uid
   * @param: isdb
   * @param: tabname
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:56
  * @author wj
  */
  public TResult getFormsFieldsbyLifeID(String conflict_id,String uid,String isdb,String tabname) {
    TResult result=new TResult();
    String bq="";
    String userp="";
    String tb="";
    if(StrKit.notBlank(tabname)) {
      tb=" '' as role ";
      bq=" and t.attrib_21 like'%"+tabname+"%'  ";
    }else{
      tb=" t1.attrib_02 as role ";
      userp="and B.id = '"+uid+"'";
    }
    List<Record> _returnnodes=new ArrayList<Record>();
    if(StrKit.notBlank(isdb) && isdb.trim().equals("1")){
      _returnnodes= Db.find("select distinct  t.*, t1.attrib_02 as role\n" +
              "from s_lifecyc_example_node t\n" +
              "\tleft join s_lifecyc_example_node_per t1 on t.conflict_id = t1.row_id\n" +
              "\tleft join TS_user B on t1.ATTRIB_01 = B.id\n" +
              "\tleft join fn_form_data f on t.attrib_12 = f.attrib_01 and f.attrib_02=t.conflict_id\n" +
              " left join s_lifecyc_example_node_acc c1\n" +
              " on t.conflict_id = c1.row_id\n" +
              "\tleft join s_lifecyc_example_node_fil e\n" +
              "  on t.conflict_id = e.row_id\n" +
              "where t.row_id =?"
              +userp+bq+" and  date_format(t.attrib_14,'%Y-%m-%d')>= date_format(now(),'%Y-%m-%d') and   ((f.attrib_101 = '0' and t1.attrib_02='AUDIT') )\n" +
              "order by t.attrib_11", conflict_id);
    }else{
      _returnnodes = Db.find("SELECT distinct t.*,"+tb+" FROM s_lifecyc_example_node t  left join s_lifecyc_example_node_per t1 on t.conflict_id=t1.row_id LEFT JOIN ts_user B " +
              "  ON t1.ATTRIB_01 = B.conflict_id " +
              "   where t.row_id=?  "+userp+bq+" order by t.attrib_11", conflict_id);
    }


    if(_returnnodes!=null){
      for(Record rs : _returnnodes){



        List<Record> _returfs = Db.find("select * from fn_form where id=?  order by id desc", rs.getStr("attrib_12"));
        rs.set("form",_returfs);

        if(_returfs!=null){
          for(Record ds : _returfs){
            List<Record> _returds = Db.find("select * from fn_form_field where form_id=? and state=1 order by form_id desc", ds.getStr("id"));

            ds.set("field",_returds);

            List<Record> _returdatas = Db.find("select * from fn_form_data where attrib_01=? and attrib_02=? and modification_num=0  order by last_upd desc", ds.getStr("id"),rs.getStr("conflict_id"));
            ds.set("data",_returdatas);
          }

        }
      }
      result.setMessage("获取成功！");
      result.setData(_returnnodes);
      result.isSuccess();
    }else{
      result.isFail();
      result.setMessage("该用户无权限节点，获取失败！");
    }
    return  result;

  }











  /**
  * @MethodName: saveOrUpdateByModelName
  * @Description: 模型存证
  * @param:
  * @return rapid.core.TResult
  * @throws
  * @date 2023/10/17 15:53
  * @author jhf
  */
  public TResult saveOrUpdateByModelName(String modelName ,String par_row_id ,FnFormData fnFormData)  {
    //判断是否存在，存在更新否则新建
   if (fnFormData.getConflictId()==null||"".equals(fnFormData.getConflictId())){

     int insert = (int) CustomDb.updateWithExceptionHandling("INSERT INTO "+modelName+" (CONFLICT_ID, row_id, PAR_row_id, CREATED, CREATED_BY, LAST_UPD, LAST_UPD_BY, MODIFICATION_NUM, EIM_SOURCE, attrib_01, attrib_02, attrib_03, attrib_04, attrib_05, attrib_06, attrib_07, attrib_08, attrib_09, attrib_10, attrib_11, attrib_12, attrib_13, attrib_14, attrib_15, attrib_16, attrib_17, attrib_18, attrib_19, attrib_20, attrib_21, attrib_22, attrib_23, attrib_24, attrib_25, attrib_26, attrib_27, attrib_28, attrib_29, attrib_30, attrib_31, attrib_32, attrib_33, attrib_34, attrib_35, attrib_36, attrib_37, attrib_38, attrib_39, attrib_40)\n" +
             "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
             fnFormData.get("CONFLICT_ID"),
             fnFormData.get("row_id"),
             par_row_id,
             fnFormData.get("CREATED"),
             fnFormData.get("CREATED_BY"),
             fnFormData.get("LAST_UPD"),
             fnFormData.get("LAST_UPD_BY"),
             fnFormData.get("MODIFICATION_NUM"),
             fnFormData.get("EIM_SOURCE"),
             fnFormData.get("attrib_01"),
             fnFormData.get("attrib_02"),
             fnFormData.get("attrib_03"),
             fnFormData.get("attrib_04"),
             fnFormData.get("attrib_05"),
             fnFormData.get("attrib_06"),
             fnFormData.get("attrib_07"),
             fnFormData.get("attrib_08"),
             fnFormData.get("attrib_09"),
             fnFormData.get("attrib_10"),
             fnFormData.get("attrib_11"),
             fnFormData.get("attrib_12"),
             fnFormData.get("attrib_13"),
             fnFormData.get("attrib_14"),
             fnFormData.get("attrib_15"),
             fnFormData.get("attrib_16"),
             fnFormData.get("attrib_17"),
             fnFormData.get("attrib_18"),
             fnFormData.get("attrib_19"),
             fnFormData.get("attrib_20"),
             fnFormData.get("attrib_21"),
             fnFormData.get("attrib_22"),
             fnFormData.get("attrib_23"),
             fnFormData.get("attrib_24"),
             fnFormData.get("attrib_25"),
             fnFormData.get("attrib_26"),
             fnFormData.get("attrib_27"),
             fnFormData.get("attrib_28"),
             fnFormData.get("attrib_29"),
             fnFormData.get("attrib_30"),
             fnFormData.get("attrib_31"),
             fnFormData.get("attrib_32"),
             fnFormData.get("attrib_33"),
             fnFormData.get("attrib_34"),
             fnFormData.get("attrib_35"),
             fnFormData.get("attrib_36"),
             fnFormData.get("attrib_37"),
             fnFormData.get("attrib_38"),
             fnFormData.get("attrib_39"),
             fnFormData.get("attrib_40")).getData();
     if (insert>0){
       return TResult.success();
     }else {
       return TResult.fail();
     }

   }else {
     int update = (int) CustomDb.updateWithExceptionHandling("UPDATE  " +modelName+
             " SET \n" +
             "  row_id = ?,\n" +
             "  PAR_row_id = ?,\n" +
             "  CREATED = ?,\n" +
             "  CREATED_BY = ?,\n" +
             "  LAST_UPD = ?,\n" +
             "  LAST_UPD_BY = ?,\n" +
             "  MODIFICATION_NUM = ?,\n" +
             "  EIM_SOURCE = ?,\n" +
             "  attrib_01 = ?,\n" +
             "  attrib_02 = ?,\n" +
             "  attrib_03 = ?,\n" +
             "  attrib_04 = ?,\n" +
             "  attrib_05 = ?,\n" +
             "  attrib_06 = ?,\n" +
             "  attrib_07 = ?,\n" +
             "  attrib_08 = ?,\n" +
             "  attrib_09 = ?,\n" +
             "  attrib_10 = ?,\n" +
             "  attrib_11 = ?,\n" +
             "  attrib_12 = ?,\n" +
             "  attrib_13 = ?,\n" +
             "  attrib_14 = ?,\n" +
             "  attrib_15 = ?,\n" +
             "  attrib_16 = ?,\n" +
             "  attrib_17 = ?,\n" +
             "  attrib_18 = ?,\n" +
             "  attrib_19 = ?,\n" +
             "  attrib_20 = ?,\n" +
             "  attrib_21 = ?,\n" +
             "  attrib_22 = ?,\n" +
             "  attrib_23 = ?,\n" +
             "  attrib_24 = ?,\n" +
             "  attrib_25 = ?,\n" +
             "  attrib_26 = ?,\n" +
             "  attrib_27 = ?,\n" +
             "  attrib_28 = ?,\n" +
             "  attrib_29 = ?,\n" +
             "  attrib_30 = ?,\n" +
             "  attrib_31 = ?,\n" +
             "  attrib_32 = ?,\n" +
             "  attrib_33 = ?,\n" +
             "  attrib_34 = ?,\n" +
             "  attrib_35 = ?,\n" +
             "  attrib_36 = ?,\n" +
             "  attrib_37 = ?,\n" +
             "  attrib_38 = ?,\n" +
             "  attrib_39 = ?,\n" +
             "  attrib_40 = ?\n" +
             "WHERE \n" +
             "  CONFLICT_ID = ?",
             fnFormData.get("row_id"),
             par_row_id,
             fnFormData.get("CREATED"),
             fnFormData.get("CREATED_BY"),
             fnFormData.get("LAST_UPD"),
             fnFormData.get("LAST_UPD_BY"),
             fnFormData.get("MODIFICATION_NUM"),
             fnFormData.get("EIM_SOURCE"),
             fnFormData.get("attrib_01"),
             fnFormData.get("attrib_02"),
             fnFormData.get("attrib_03"),
             fnFormData.get("attrib_04"),
             fnFormData.get("attrib_05"),
             fnFormData.get("attrib_06"),
             fnFormData.get("attrib_07"),
             fnFormData.get("attrib_08"),
             fnFormData.get("attrib_09"),
             fnFormData.get("attrib_10"),
             fnFormData.get("attrib_11"),
             fnFormData.get("attrib_12"),
             fnFormData.get("attrib_13"),
             fnFormData.get("attrib_14"),
             fnFormData.get("attrib_15"),
             fnFormData.get("attrib_16"),
             fnFormData.get("attrib_17"),
             fnFormData.get("attrib_18"),
             fnFormData.get("attrib_19"),
             fnFormData.get("attrib_20"),
             fnFormData.get("attrib_21"),
             fnFormData.get("attrib_22"),
             fnFormData.get("attrib_23"),
             fnFormData.get("attrib_24"),
             fnFormData.get("attrib_25"),
             fnFormData.get("attrib_26"),
             fnFormData.get("attrib_27"),
             fnFormData.get("attrib_28"),
             fnFormData.get("attrib_29"),
             fnFormData.get("attrib_30"),
             fnFormData.get("attrib_31"),
             fnFormData.get("attrib_32"),
             fnFormData.get("attrib_33"),
             fnFormData.get("attrib_34"),
             fnFormData.get("attrib_35"),
             fnFormData.get("attrib_36"),
             fnFormData.get("attrib_37"),
             fnFormData.get("attrib_38"),
             fnFormData.get("attrib_39"),
             fnFormData.get("attrib_40"),
             fnFormData.get("CONFLICT_ID")).getData();
     if (update>0){
       return TResult.success();
     }else {
       return TResult.fail();
     }
     
   }




  }

  /**
   * 验证操作权限(绑定模型的动态表单)
   */
  public TResult checkOperationLimits_model(Record old, String operation, Authuser user) throws ParseException {
    if (!"add".equals(operation)) {
      if (!old.get("created_by").equals(user.getId())) {
        return TResult.fail().msg("只能操作当前用户新增数据。");
      }

      if (AuditStatusEnumCls.Pass.getValue().equals(old.get("audit_state"))) {
        return TResult.fail().msg("当前提交数据已经审核，不可再操作。");
      }
    }

    TResult _r = CheckNodeIsTimeOut(old.getStr("lifenode_id"));
    if (_r.isFail()) {
      return _r;
    }

    return success();
  }
  /**
   * 检查是否重复(绑定模型的动态表单)
   *
   * @return
   */
  public TResult checkDulpicate_model(String id, String title, String fieldKey, String fieldValue,String keyid,String modelname) {
    FormField temp;

    if (StrKit.notBlank(keyid)) {
      if (id != null) {
        temp = FormField.dao.findFirst("select * from " + modelname + "  where conflict_id <> ? and lifenode_id=?  and " + fieldKey + "=?", id, keyid,fieldValue);
      } else {
        temp = FormField.dao.findFirst("select * from " + modelname + "  where   " + fieldKey + "=? and lifenode_id=? ", fieldValue,keyid);
      }
    }
    else {
      if (id != null) {
        temp = FormField.dao.findFirst("select * from " + modelname + "  where conflict_id <> ?   and " + fieldKey + "=?", id,fieldValue);
      } else {
        temp = FormField.dao.findFirst("select * from " + modelname + "  where   " + fieldKey + "=?  ", fieldValue);
      }
    }

    if (temp != null) {
      return TResult.fail().msg(title + "有重复。");
    }

    return success();
  }


  /**
   * 生成自动编码
   * @param field
   * @return
   */
  protected String getAutocode(FormField field){

    if(WhetherEnumCls.YES.getValue().equals(field.getIsAutocode())){

      String maxNum = Helper.updateSerialNumberByDate(DateKit.getDate(), field.getId());
      String prefix1 = getPrefixStr(field.getPrefix1());
      String prefix2 = getPrefixStr(field.getPrefix2());
      String separator = field.getSeparator();

      return prefix1 + separator + prefix2 + separator + StrKit.padLeft(Integer.toString(Integer.parseInt(maxNum)), Integer.valueOf(field.getSerialNumber()), "0");
    }else{

      return "";
    }
  }
  /**
   * 生成自动日期格式
   * @param str
   * @return
   */
  protected String getPrefixStr(String str){

    String prefix = "";
    if("年月日".equals(str)){

      prefix = DateKit.format(DateKit.getDate(), "yyyyMMdd");
    }else if("年月".equals(str)){

      prefix = DateKit.format(DateKit.getDate(), "yyyyMM");
    }else if("年".equals(str)){

      prefix = DateKit.format(DateKit.getDate(), "yyyy");
    }else{

      prefix = str;
    }

    return prefix;
  }


}
